<?php

namespace App\Http\Controllers\Api;

use App\Jobs\AttachIpAddressJob;

use App\Models\Posts\WxPost;
use App\Models\Posts\WxPost as Model;
use App\Models\Circle\WxCircle;
use App\Models\Shop\WxShopGoods;
use App\Models\User\WxUser;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\PostUtils;
use App\Wen\Utils\Settings;
use App\Http\Controllers\Api\Repositories\PostsRepositores;
use App\Models\WxSlideshow;
use App\Wen\Utils\ShopUtils;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class IndexController extends BaseController
{

    public function test(Request $request)
    {
        dd(_mini_emoji('[微笑]'));
    }

    /**
     * 圈子轮播图
     */
    public function circles_banner()
    {
        if(Settings::get('app_circles_banner', '', true)){
            $banner = WxSlideshow::wherein('id', explode(',', Settings::get('app_circles_banner', '', true)))->orderBy('sort', 'desc')->get();
            return $this->success($banner);
        }
        return $this->fail(200003, []);
    }


    public function getPosts(Request $request)
    {
        $uid = $request->uid;
        $type = (int)($request->type);
        $plateId = $request->plate_id;
        $channel = $request->channel;
        global $__MINI_GLOBAL_SCENE__;
        if(_empty_($channel, true)){
            $channel = 1;
        }else{
            $channel = _abs($channel);
        }
        $city = _empty_default_($request->city, '');
        if(_empty_($city) || $city == '全国' || $city == '重新定位' || $city == '定位中'){
            $city = '';
        }

        $limit = $request->input('limit', 10);
        // 我关注的笔记列表
        if(_empty_($plateId)){
            if($__MINI_GLOBAL_SCENE__ == 165){
                $is_waterfall = false;
                $tab_ = 1;
            }else{
                $index_tab = json_decode(Settings::get('app_index_tab', '', true), true);
                if(_empty_($index_tab)){
                    return $this->fail(200008, [], '管理员暂未配置首页Tab数据');
                }
                if(!isset($index_tab[$type])){
                    return $this->fail(200008, [], '管理员暂未配置该tab');
                }
                $tab_ = $index_tab[$type]['type'];
                $is_waterfall = _array_key($index_tab[$type], 'waterfall', '0') == '1';
                $is_force = _array_key($index_tab[$type], 'force', '0') == '1';
                $target_id = _array_key($index_tab[$type], 'target', '');
                global $__MINI_GLOBAL_DEVICE__,$__MINI_GLOBAL_MODE__;
                if($channel === 0){
                    $tab_ = 0;
                    $is_waterfall = false;
                }else if($channel === 2){
                    $tab_ = 7;
                    $is_waterfall = true;
                }else if($channel === 1){
                    if($is_force){

                    }else{
                        $diy_list_style = mini_current_user(2, 'diy_scene_1_post_list_style');
                        if($diy_list_style == 3){
                            $is_waterfall = true;
                        }else if($diy_list_style == 2){
                            $is_waterfall = false;
                        }
                    }
                }
            }

            if ($tab_ == 0) {
                $data = PostsRepositores::followPosts($uid, $limit, $is_waterfall);
            }

            // 推荐的笔记列表
            else if ($tab_ == 1) {
                $data = PostsRepositores::list($uid, $limit, $is_waterfall, $city);
            }


            // 热榜的笔记列表
            else if ($tab_ == 2 || $tab_ == 9) {
                $data = PostsRepositores::hotPosts($uid, $limit, $is_waterfall, $tab_ == 2);
            }

            else if ($tab_ == 3) {

                $shop_classifys = Settings::get('app_index_shop_classify', []);
                if(_empty_($shop_classifys)){
                    $data = WxShopGoods::where('state', 1)->orderBy('sort', 'desc')->orderBy('id', 'desc')->simplePaginate($limit);
                }else{
                    $ban_ids = ShopUtils::get_ban_classes($request->header('device', 'mp'));
                    if($ban_ids){
                        $data = WxShopGoods::where('state', 1)->whereIn('classify_id', $shop_classifys)->whereNotIn('classify_id', $ban_ids)->orderBy('sort', 'desc')->orderBy('id', 'desc')->simplePaginate($limit);
                    }else{
                        $data = WxShopGoods::where('state', 1)->whereIn('classify_id', $shop_classifys)->orderBy('sort', 'desc')->orderBy('id', 'desc')->simplePaginate($limit);
                    }
                }
            }

            // 板块
            else if ($tab_ == 4) {
                $plate_ids = explode(',', _array_key($index_tab[$type], 'plate_ids', ''));
                $circleIds = WxCircle::whereIn('plate_id', $plate_ids)->pluck('id');

                $query = (new Model())
                    ->where('is_examine', 1)
                    ->where('posts_state', 0);

                // 控制视频隐藏
                if($__MINI_GLOBAL_DEVICE__ != 'mp'){
                    global $__MINI_GLOBAL_FRONT_VERSION__;
                    // todo: 临时
                    if($__MINI_GLOBAL_FRONT_VERSION__ >= '1.2.2.24'){

                    }else {
                        $query = $query->where('is_wechat_sph', 0);
                    }
                }
                if($__MINI_GLOBAL_MODE__ == 'examine'){
                    $query = $query->where('post_type', '<>', 'video');
                }

                $data = $query->whereIn('circle_id', $circleIds)
                    ->orderBy('id', 'desc')
                    ->simplePaginate($limit, FieldUtils::postInfoColums());

                if($is_waterfall){
                    PostUtils::reset_loop();
                    $data->map(function ($v, $k) use ($uid){
                        return PostUtils::WaterfallProcess($k, $v,1);
                    });
                }else {
                    $data = PostsRepositores::postsParame($data, $uid, 1);
                }
            }
            // 视频
            else if ($tab_ == 5) {

                $query = (new Model())
                    ->where('is_examine', 1)
                    ->where('posts_state', 0);

                // 控制视频隐藏
                if($__MINI_GLOBAL_DEVICE__ != 'mp'){
                    global $__MINI_GLOBAL_FRONT_VERSION__;
                    // todo: 临时
                    if($__MINI_GLOBAL_FRONT_VERSION__ >= '1.2.2.24'){

                    }else {
                        $query = $query->where('is_wechat_sph', 0);
                    }
                }
                if($__MINI_GLOBAL_MODE__ == 'examine'){
                    $query = $query->where('post_type', '<>', 'video');
                }

                $data = $query->has('video')
                    ->orderBy('id', 'desc')
                    ->simplePaginate($limit, FieldUtils::postInfoColums());
                if($is_waterfall){
                    PostUtils::reset_loop();
                    $data->map(function ($v, $k) use ($uid){
                        return PostUtils::WaterfallProcess($k, $v,1);
                    });
                }else {
                    $data = PostsRepositores::postsParame($data, $uid, 1);
                }
            }
            // 长图文
            else if ($tab_ == 6) {

                $query = (new Model())
                    ->where('is_examine', 1)
                    ->where('posts_state', 0);

                // 控制视频隐藏
                if($__MINI_GLOBAL_DEVICE__ != 'mp'){
                    global $__MINI_GLOBAL_FRONT_VERSION__;
                    // todo: 临时
                    if($__MINI_GLOBAL_FRONT_VERSION__ >= '1.2.2.24'){

                    }else {
                        $query = $query->where('is_wechat_sph', 0);
                    }
                }
                if($__MINI_GLOBAL_MODE__ == 'examine'){
                    $query = $query->where('post_type', '<>', 'video');
                }

                $data = $query->where('post_type', 'single')
                    ->orderBy('id', 'desc')
                    ->simplePaginate($limit, FieldUtils::postInfoColums());

                if($is_waterfall){
                    PostUtils::reset_loop();
                    $data->map(function ($v, $k) use ($uid){
                        return PostUtils::WaterfallProcess($k, $v,1);
                    });
                }else {
                    $data = PostsRepositores::postsParame($data, $uid, 1);
                }
            }


            else if ($tab_ == 7) {
                if($uid > 0){
                    $user = WxUser::find($uid);
                    global $__MINI_GLOBAL_IP__;

                    $longitude = $user->longitude;
                    $latitude = $user->latitude;

                    if(_empty_($longitude) && _empty_($latitude)){
                        $res = _ip_address($__MINI_GLOBAL_IP__);
                        if(_empty_($res)){
                            return $this->fail(503003);
                        }
                        $longitude = $res['longitude'];
                        $latitude = $res['latitude'];
                        WxUser::where('id', $uid)->update([
                            'ip' =>  $__MINI_GLOBAL_IP__
                        ]);
                        AttachIpAddressJob::dispatch(2, $uid)->delay(2);
                    }

                    $the_base_id = Cache::remember('posts:new:1000', 3600 * 5, function (){
                        $base_id = WxPost::where('is_examine', 1)->where('posts_state', 0)->orderBy('id', 'desc')->skip(500)->value('id');
                        return $base_id > 0 ? $base_id : 0;
                    });

                    $query = WxPost::select(DB::raw('*, ( 6378137 * acos( cos( radians('.$latitude.') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians('.$longitude.') ) + sin( radians('.$latitude.') ) * sin( radians( latitude ) ) ) ) AS distance'))
                        ->where('id', '>', $the_base_id)
                        ->where('is_examine', 1)
                        ->where('posts_state', 0);

                    // 控制视频隐藏
                    if($__MINI_GLOBAL_DEVICE__ != 'mp'){
                        global $__MINI_GLOBAL_FRONT_VERSION__;
                        // todo: 临时
                        if($__MINI_GLOBAL_FRONT_VERSION__ >= '1.2.2.24'){

                        }else {
                            $query = $query->where('is_wechat_sph', 0);
                        }
                    }
                    if($__MINI_GLOBAL_MODE__ == 'examine'){
                        $query = $query->where('post_type', '<>', 'video');
                    }

                    $data = $query->where('user_id', '<>', $uid)
                        ->having('distance', '<', 100000)
                        ->inRandomOrder()
                        ->simplePaginate($limit, FieldUtils::postInfoColums());

                    if($is_waterfall){
                        PostUtils::reset_loop();
                        $data->map(function ($v, $k) use ($uid){
                            return PostUtils::WaterfallProcess($k, $v,1);
                        });
                    }else {
                        $data = PostsRepositores::postsParame($data, $uid, 1);
                    }

                }else{
                    return $this->fail(200003, [], '没有获取到您的经纬度信息');
                }
            }else if ($tab_ == 8) {
                // 圈子
                $circleIds = explode(',', $target_id);
                if(_empty_($circleIds)){
                    return null;
                }

                $query = (new Model())
                    ->where('is_examine', 1)
                    ->where('posts_state', 0);

                // 控制视频隐藏
                if($__MINI_GLOBAL_DEVICE__ != 'mp'){
                    global $__MINI_GLOBAL_FRONT_VERSION__;
                    // todo: 临时
                    if($__MINI_GLOBAL_FRONT_VERSION__ >= '1.2.2.24'){

                    }else {
                        $query = $query->where('is_wechat_sph', 0);
                    }
                }
                if($__MINI_GLOBAL_MODE__ == 'examine'){
                    $query = $query->where('post_type', '<>', 'video');
                }

                $data = $query->whereIn('circle_id', $circleIds)
                    ->orderBy('id', 'desc')
                    ->simplePaginate($limit, FieldUtils::postInfoColums());

                if($is_waterfall){
                    PostUtils::reset_loop();
                    $data->map(function ($v, $k) use ($uid){
                        return PostUtils::WaterfallProcess($k, $v,1);
                    });
                }else {
                    $data = PostsRepositores::postsParame($data, $uid, 1);
                }
            }

            return $this->success($data);
        }else{
            $data = PostsRepositores::getListByPlate($uid, $plateId, $limit);
            return $this->success($data);
        }
    }
}
